package org.kumas.sgrpc.remoting.transport;

import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;

import org.kumas.sgrpc.common.URL;
import org.kumas.sgrpc.common.extension.ExtensionLoader;
import org.kumas.sgrpc.common.threadpool.manager.ExecutorRepository;
import org.kumas.sgrpc.common.utils.ExecutorUtil;
import org.kumas.sgrpc.common.utils.NetUtils;
import org.kumas.sgrpc.remoting.Channel;
import org.kumas.sgrpc.remoting.ChannelHandler;
import org.kumas.sgrpc.remoting.Codec;
import org.kumas.sgrpc.remoting.Constants;
import org.kumas.sgrpc.remoting.RemotingException;
import org.kumas.sgrpc.remoting.RemotingServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.kumas.sgrpc.common.constants.CommonConstants.ANYHOST_KEY;
import static org.kumas.sgrpc.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.kumas.sgrpc.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.kumas.sgrpc.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.kumas.sgrpc.remoting.Constants.ACCEPTS_KEY;
import static org.kumas.sgrpc.remoting.Constants.DEFAULT_ACCEPTS;
import static org.kumas.sgrpc.remoting.Constants.DEFAULT_IDLE_TIMEOUT;
import static org.kumas.sgrpc.remoting.Constants.IDLE_TIMEOUT_KEY;

/**
 *
 * @author KumasZhang
 * @version 1.0
 * @since 2021-07-15 08:11
 */
public abstract class AbstractServer extends AbstractEndpoint implements RemotingServer, ChannelHandler {


    protected static final String SERVER_THREAD_POOL_NAME = "SgrpcServerHandler";
    private static final Logger logger = LoggerFactory.getLogger(AbstractServer.class);
    private final ChannelHandler handler;
    protected ExecutorService executor;
    private InetSocketAddress localAddress;
    private InetSocketAddress bindAddress;
    private int accepts;
    private int idleTimeout;
    private Codec codec;
    private int timeout;
    private int connectTimeout;
    private volatile URL url;

    private volatile boolean closing;

    private volatile boolean closed;

    private ExecutorRepository executorRepository = ExtensionLoader.getExtensionLoader(ExecutorRepository.class).getDefaultExtension();

    public AbstractServer(URL url, ChannelHandler handler) throws RemotingException {
        if (url == null) {
            throw new IllegalArgumentException("url == null");
        }
        if (handler == null) {
            throw new IllegalArgumentException("handler == null");
        }
        this.url = url;
        this.handler = handler;

        this.codec = getChannelCodec(url);
        this.timeout = url.getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT);
        this.connectTimeout = url.getPositiveParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT);

        localAddress = getUrl().toInetSocketAddress();
        String bindIp = getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost());
        int bindPort = getUrl().getParameter(Constants.BIND_PORT_KEY, getUrl().getPort());

        if (url.getParameter(ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) {
            bindIp = ANYHOST_VALUE;
        }

        bindAddress = new InetSocketAddress(bindIp, bindPort);
        this.accepts = url.getParameter(ACCEPTS_KEY, DEFAULT_ACCEPTS);
        this.idleTimeout = url.getParameter(IDLE_TIMEOUT_KEY, DEFAULT_IDLE_TIMEOUT);

        try {
            doOpen();
            if (logger.isInfoEnabled()) {
                logger.info("Start " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress());
            }
        } catch (Throwable t) {
            throw new RemotingException(url.toInetSocketAddress(), null, "Failed to bind " + getClass().getSimpleName()
                + " on " + getLocalAddress() + ", cause: " + t.getMessage(), t);
        }
        executor = executorRepository.createExecutorIfAbsent(url);

    }

    protected abstract void doOpen() throws Throwable;

    protected abstract void doClose() throws Throwable;

    public InetSocketAddress getBindAddress() {
        return bindAddress;
    }

    public int getAccepts() {
        return accepts;
    }

    public int getIdleTimeout() {
        return idleTimeout;
    }

    protected int getTimeout() {
        return timeout;
    }

    protected int getConnectTimeout() {
        return connectTimeout;
    }

    @Override
    public URL getUrl() {
        return url;
    }

    protected void setUrl(URL url) {
        if (url == null) {
            throw new IllegalArgumentException("url == null");
        }
        this.url = url;
    }

    @Override
    public ChannelHandler getChannelHandler() {
        if (handler instanceof ChannelHandlerDelegate) {
            return ((ChannelHandlerDelegate) handler).getHandler();
        } else {
            return handler;
        }
    }

    @Override
    public InetSocketAddress getLocalAddress() {
        return localAddress;
    }

    @Override
    public void send(Object message) throws RemotingException {
        send(message, url.getParameter(Constants.SENT_KEY, false));
    }

    @Override
    public void send(Object message, boolean sent) throws RemotingException {
        Collection<Channel> channels = getChannels();
        for (Channel channel : channels) {
            if (channel.isConnected()) {
                channel.send(message, sent);
            }
        }
    }

    @Override
    public void close() {
        if (logger.isInfoEnabled()) {
            logger.info("Close " + getClass().getSimpleName() + " bind " + getBindAddress() + ", export " + getLocalAddress());
        }
        ExecutorUtil.shutdownNow(executor, 100);
        closed = true;
        try {
            doClose();
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
        }
    }

    @Override
    public void close(int timeout) {
        ExecutorUtil.gracefulShutdown(executor, timeout);
        close();
    }

    @Override
    public void startClose() {
        if (isClosed()) {
            return;
        }
        closing = true;
    }

    @Override
    public boolean isClosed() {
        return closed;
    }

    @Override
    public void connected(Channel channel) throws RemotingException {
        if (this.isClosing() || this.isClosed()) {
            logger.warn("Close new channel " + channel + ", cause: server is closing or has been closed. For example, receive a new connect request while in shutdown process.");
            channel.close();
            return;
        }
        if (accepts > 0 && getChannels().size() > accepts) {
            logger.error("Close channel " + channel + ", cause: The server " + channel.getLocalAddress() + " connections greater than max config " + accepts);
            channel.close();
            return;
        }

        handler.connected(channel);
    }

    @Override
    public void disconnected(Channel channel) throws RemotingException {
        Collection<Channel> channels = getChannels();
        if (channels.isEmpty()) {
            logger.warn("All clients has disconnected from " + channel.getLocalAddress() + ". You can graceful shutdown now.");
        }
        handler.disconnected(channel);
    }

    @Override
    public void sent(Channel channel, Object message) throws RemotingException {
        if (closed) {
            return;
        }
        handler.sent(channel, message);
    }

    @Override
    public void received(Channel channel, Object message) throws RemotingException {
        if (closed) {
            return;
        }
        handler.received(channel, message);
    }

    @Override
    public void caught(Channel channel, Throwable exception) throws RemotingException {
        handler.caught(channel, exception);
    }

    public boolean isClosing() {
        return closing && !closed;
    }

    protected Codec getCodec() {
        return codec;
    }
}
